/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.defines;

import java.util.Map;

import com.cred.industries.platform.dao.CustomerRolesDAOFactory;
import com.cred.industries.platform.dao.ICustomerRolesDAO;

/**
 * roles that match the ones in the DB.
 * It will automatically sync to the values in the DB
 */
public enum Role {

	ADMIN (),
	CS (),
	USER (), 
	GUEST ();
	
	/**
	 * to use with the @rolesAllowed tag we need these to be constant
	 */
	public static final String ADMIN_STRING = "ADMIN";
	public static final String CS_STRING = "CS";
	public static final String USER_STRING = "USER";
	public static final String GUEST_STRING = "GUEST";
	
	private int value;
	
	/**
	 * 
	 * @return the priority of this role. the higher the number the more powerful the role. 
	 */
	public int getRolePriority() { return value; }

	Role() {
		value = getRolePriority(this.toString());
	}
	
	/**
	 * converts a int to a role
	 * @param i the int version of the role
	 * @return the role Enum
	 */
	public static Role convert(int i) {
		
		for (Role current : values()) {
			if (current.getRolePriority() == i) {
				return current;
			}
		}
		
		return GUEST;
	}
	
	/**
	 * converts a string to a role
	 * @param i the string version of the role
	 * @return the role Enum
	 */
	public static Role convert(String i) {
		
		for (Role current : values()) {
			if (current.toString().equalsIgnoreCase(i)) {
				return current;
			}
		}
		
		return GUEST;
	}
	

	/**
	 * to keep the roles in sync with the Db we 
	 * get the role value from the DAO
	 * @param Role int that matches with the DB
	 * @return
	 */
	private int getRolePriority(String Role) {
		
		Map<String, Integer> roleMap;
		ICustomerRolesDAO rolesDAO = CustomerRolesDAOFactory.create();
		roleMap = rolesDAO.getRoles();
		
		if(roleMap.containsKey(Role)) {
			return roleMap.get(Role);
		}
		
		return 999;
	}
}
